package com.basics.common.utils;

import com.basics.common.exception.BadRequestException;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLIntegrityConstraintViolationException;

/**功能描述：异常工具
 * @Author Geordie
 * @ClassName ThrowableUtil
 * @Date 2021/7/8
 * @Annotation
 */
public class ThrowableUtil {

    /**
     * 获取堆栈信息
     */
    public static String getStackTrace(Throwable throwable){
        StringWriter sw = new StringWriter();
        try (PrintWriter pw = new PrintWriter(sw)) {
            throwable.printStackTrace(pw);
            return sw.toString();
        }
    }

    public static void throwForeignKeyException(Throwable e, String msg){
        Throwable t = e.getCause();
        //SQLIntegrityConstraintViolationException>>>ConstraintViolationException
        while ((t != null) && !(t instanceof SQLIntegrityConstraintViolationException)) {
            t = t.getCause();
        }
        if (t != null) {
            throw new BadRequestException(msg);
        }
        assert false;
        throw new BadRequestException("删除失败：" + t.getMessage());
    }


}
